package com.quasar.hpatient.view.personal.setup;
import android.app.Activity;
import android.content.Intent;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.TextView;

import com.quasar.hpatient.MainAppliaction;
import com.quasar.hpatient.R;
import com.quasar.hpatient.base.BaseActivity;
import com.quasar.hpatient.choicePhoto.PhotoSelectorActivity;
import com.quasar.hpatient.constant.ConstantManger;
import com.quasar.hpatient.model.controllermodel.PictureConstant;
import com.quasar.hpatient.model.custommodel.PhotoModel;
import com.quasar.hpatient.model.httpmodel.DataStateResult;
import com.quasar.hpatient.model.medicalmodel.PatientInfoData;
import com.quasar.hpatient.network.RetrofitConnection;
import com.quasar.hpatient.utils.SystemTool;
import com.quasar.hpatient.view.ImageViewpageActivity_;
import com.quasar.hpatient.view.adapter.MyGrideViewAdapter;
import com.quasar.hpatient.widget.AutoHeightGridView;
import com.vise.log.ViseLog;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.OptionsItem;
import org.androidannotations.annotations.OptionsMenu;
import org.androidannotations.annotations.ViewById;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

/**
 * 意见反馈
 */
@OptionsMenu(R.menu.menu_submit)
@EActivity(R.layout.activity_feedback)
public class FeedbackActivity extends BaseActivity implements PictureConstant.updateUiInit {

    PatientInfoData patient= MainAppliaction.getInstance().getPatient();
    String userCode=MainAppliaction.getInstance().getUserCode();
    //用户类别
    String userType= ConstantManger.userType;
    PictureConstant pictureConstant;
    MyGrideViewAdapter myGrideViewAdapter;
    public static final int PHOTO_MAX_COUNT = 100;//设置选中图片的最大数量
    private int SELECT_IMAGE_CODE = 101;
    public static ArrayList<String> photos = new ArrayList<>();
    //保存当如化验单图片
    public static ArrayList<PhotoModel> minitDatas = new ArrayList();
    private final String SATTS="FeedbackActivity";
    String cover="";

    @ViewById(R.id.main_toolbar)
    Toolbar main_toolbar;
    //反馈意见
    @ViewById(R.id.message)
    EditText message;
    //联系电话
    @ViewById(R.id.feedback_et_phone)
    TextView feedback_et_phone;
    @ViewById(R.id.gridView)
    AutoHeightGridView gridView;


    @AfterViews
    void init(){
        ViseLog.d("enter");
        initView();
        initData();
    }

    @Override
    protected void initView() {
        initToolbar();
        myGrideViewAdapter = new MyGrideViewAdapter(this, minitDatas);
        gridView.setAdapter(myGrideViewAdapter);
        feedback_et_phone.setText(patient.getPhone());
        pictureConstant=new PictureConstant(this);

        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (position == minitDatas.size()) {
                    selectPic();
                } else {
                    //跳转图片预览界面
                    //传递标识显示隐藏删除图片按钮
                    String stats = "TestRecordActivity";
                    ImageViewpageActivity_.intent(FeedbackActivity.this).Photolist(photos).position(position).STATS(SATTS).photoModelDatas(minitDatas).start();
                }

            }
        });
    }

    //选择图片
    public void selectPic() {
        Intent intent = new Intent(this, PhotoSelectorActivity.class);
        intent.putExtra(PhotoSelectorActivity.KEY_MAX, PHOTO_MAX_COUNT);
        intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);

        if (minitDatas.size() > 0) {
            intent.putExtra("datas", minitDatas);
        }
        startActivityForResult(intent, SELECT_IMAGE_CODE);

    }

    @Override
    protected void initData() {

    }

    //提交
    @OptionsItem(R.id.action_submit)
    public void action_submit(){
        String msg=message.getText().toString().trim();
        if(msg.length()==0){
            msg("请填写反馈意见");
            return;
        }
        showDialog();
        if(photos.size()!=0){
            List<File> fileList=new ArrayList<>();
            for(int i=0;i<photos.size();i++){
                fileList.add(new File(photos.get(i)));
            }
            pictureConstant.PostPicture(fileList);
        }else{
            PostFeedback(cover,msg);
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode != Activity.RESULT_OK)
            return;
        if (requestCode == SELECT_IMAGE_CODE) {// selected image
            if (data != null && data.getExtras() != null) {
                List<PhotoModel> photosModel = (List<PhotoModel>) data.getExtras()
                        .getSerializable("photos");
                if (photosModel == null || photosModel.isEmpty()) {
                } else {
                    photos.clear();
                    minitDatas.clear();
                    ViseLog.d("图片的数据长度" + photosModel.size());
                    minitDatas.addAll(photosModel);
//                    myGrideViewAdapter.notifyDataSetChanged();

                    for (int i = 0; i < photosModel.size(); i++) {
                        photos.add(photosModel.get(i).getOriginalPath());
                    }
                }
                myGrideViewAdapter.notifyDataSetChanged();
            }

        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        minitDatas.clear();
        photos.clear();
    }

    /**
     * 意见反馈请求
     * @param cover 图片返回的路径
     * @param message  意见
     */
    public void PostFeedback(String cover,String message){
        //当前apk的版本号
        int version= SystemTool.getAppVersionCode(this);

        RetrofitConnection.getRoutineApi()
                .Feedback(patient.getId()+"",userCode,message,patient.getPhone(),version+"",cover,userType)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .doOnNext(new Consumer<DataStateResult>() {
                    @Override
                    public void accept(DataStateResult dataStateResult) throws Exception {
                        if(!dataStateResult.getMsgCode().equals("0x00000000")){
                            throw new RuntimeException();
                        }
                    }
                })
                .subscribe(new Observer<DataStateResult>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {

                    }

                    @Override
                    public void onNext(@NonNull DataStateResult dataStateResult) {
                        ViseLog.d("onNext"+dataStateResult);
                        if(dataStateResult.getMsgCode().equals("0x00000000")){
                            msg("提交成功");
                            finish();
                        }
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        ViseLog.d("onError"+e.getMessage());
                        dessDialog();
                    }

                    @Override
                    public void onComplete() {
                        ViseLog.d("onComplete");
                        dessDialog();
                    }
                });
    }

    @Override
    public void updateInit(String path) {

        String msg=message.getText().toString().trim();
        if(msg.length()==0){
            msg="";
        }
        if(path.length()>0){
            PostFeedback(path,msg);
        }

    }

    @Override
    public void onErrPhoto(String errVal) {
        if(errVal!=null){
            msg("图片上传失败"+errVal);
        }
        dessDialog();
    }
}
